package leilao;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author william
 */
public class ConnCliente implements Runnable {

    private static Socket clientSocket = null;
    private static PrintStream os = null;
    private static DataInputStream is = null;
    private static boolean closed = false;
    private String msgCliente = null;
    private static String resposta = null;

    public void conecta() {
        int portNumber = 6990; //porta deve ser a mesma do servidor..
        String host = "localhost";

        try {
            clientSocket = new Socket(host, portNumber);
            os = new PrintStream(clientSocket.getOutputStream());
            is = new DataInputStream(clientSocket.getInputStream());
        } catch (UnknownHostException e) {
            System.err.println("Impossivel alcancar o host " + host);
        } catch (IOException e) {
            System.err.println("Impossivel fazer I/O no momento com o host " + host);
        } finally {
            System.out.println("SOCKET criado com sucesso!");
            /*
             *  Cria uma Thread para o novo cliente escutar o servidor.
             */
            new Thread(new ConnCliente()).start();
            System.out.println("CRIOU A THREAD");
        }
    }

    public void enviaMsg() {
        if (clientSocket != null && os != null && is != null) {
            if (!closed) {
                if (msgCliente != null) {
                    try {
                        os.println(msgCliente);
                        System.out.println("Mensagem enviada: " + msgCliente);
                        System.out.println("THREAD 1" + Thread.currentThread().toString());
                        Thread.sleep(500);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(ConnCliente.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    }

    public void desconecta() {
        if (!closed) {
            try {
                os.close();
                is.close();
                clientSocket.close();
                System.out.println("FECHOU A CONEXAO");
            } catch (IOException e) {
                System.err.println("IOException:  " + e);
            }
        }
    }

    /**
     * @param msgCliente the msgCliente to set
     */
    public void setMsgCliente(String msgCliente) {
        this.msgCliente = msgCliente;
    }

    public void run() {
        /*
         * Keep on reading from the socket till we receive "Bye" from the
         * server. Once we received that then we want to break.
         */
        String responseLine;

        try {
            while ((responseLine = is.readLine()) != null) {
                System.out.println("THREAD 2" + Thread.currentThread().toString());
                resposta = responseLine;
                System.out.println("RESPOSTA DO SERVIDOR NA THREAD 2 =>>"+resposta);
                if (responseLine.indexOf("*** Connection Closed") != -1) {
                    break;
                }
            }
            closed = true;
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
    }

    /**
     * @return the responseLine
     */
    public String getResponseLine() {
        this.setMsgCliente(null);
        System.out.println("RESPONSE LINE >>>>>>>>>>>>>" + resposta);
        return resposta;
    }
}
